package com.ls.kdlss.ui.Login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gm.common.utils.ToastUtil;
import com.gm.lib.utils.Compress;
import com.gm.lib.utils.UploadImgAdapter;
import com.gm.lib.views.titlebar.AbTitleBar;
import com.ls.kdlss.R;
import com.ls.kdlss.util.SoundMeter;
import com.tencent.mm.sdk.modelmsg.ShowMessageFromWX;
import com.wx.android.common.util.ActivityUtil;

import java.io.File;
import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by Administrator on 2016/11/22.
 */

public class SetInfomationTwoActivity extends AppCompatActivity {


    @Bind(R.id.title_bar)
    AbTitleBar titleBar;
    @Bind(R.id.imageView7)
    ImageView imageView7;
    @Bind(R.id.tv_jishi)
    TextView tvJishi;
    @Bind(R.id.im_start)
    ImageView imStart;
    @Bind(R.id.tv_Again)
    TextView tvAgain;
    @Bind(R.id.iv_touxiang)
    ImageView ivTouxiang;
    @Bind(R.id.rl_bofangone)
    RelativeLayout rlBofangone;
    @Bind(R.id.rl_bofangtwo)
    RelativeLayout rlBofangtwo;
    @Bind(R.id.rl_bofangthree)
    RelativeLayout rlBofangthree;
    //语音操作对象
    private MediaPlayer mPlayer = null;
    private MediaRecorder mRecorder = null;
    private static final String LOG_TAG = "AudioRecordTest";

    //语音文件保存路径

    CountDownTimer countDownTimer;


    private LinearLayout del_re;
    private View rcChat_popup;
    private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
            voice_rcd_hint_tooshort;
    private Handler mHandler = new Handler();
    private ImageView chatting_mode_btn, volume;
    private ImageView img1, sc_img1;
    private long startVoiceT, endVoiceT;

    private boolean btn_vocie = true;
    private boolean isShosrt = false;
    private int flag = 1;
    private String voiceName;
    private SoundMeter mSensor;
    int haomiao = 0;
    int miao = 0;
    int fen = 0;
    int xiaoshi = 0;

    public static void lanuch(Context context) {
        ActivityUtil.startActivity(context, SetInfomationTwoActivity.class);
    }

    private UploadImgAdapter uploadImgAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_informationtwo);
        ButterKnife.bind(this);
        init();

    }

    public void init() {
        onc();
        rcChat_popup = findViewById(R.id.rcChat_popup);
        //设置sdcard的路径
        voiceName = Environment.getExternalStorageDirectory().getAbsolutePath();
        voiceName += "/pander.wav";
        titleBar.setTitleText("填写个人资料");
        titleBar.setRightButton("下一步", Color.rgb(249, 249, 249));
        titleBar.getRightButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetinfomatonThreeActivity.lanuch(SetInfomationTwoActivity.this);
                

            }
        });



        if (ContextCompat.checkSelfPermission(SetInfomationTwoActivity.this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(SetInfomationTwoActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, 111);
        }
        if (ContextCompat.checkSelfPermission(SetInfomationTwoActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(SetInfomationTwoActivity.this, new String[]{Manifest.permission.CAMERA}, 111);
        }

        imStart.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {


                int action = MotionEventCompat.getActionMasked(event);
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                         haomiao = 0;
                         miao = 0;
                         fen = 0;
                         xiaoshi = 0;

                        daoJishi(tvJishi);
                        rcChat_popup.setVisibility(View.VISIBLE);

                            onstarts();

                        break;
                    case MotionEvent.ACTION_UP:
                        rcChat_popup.setVisibility(View.GONE);
                        countDownTimer.cancel();
                        rcChat_popup.setVisibility(View.GONE);
                        if (miao>=1){
                            onstorp();
                        }else {
                            ToastUtil.show("时间太短了");
                        }


                        break;
                }
                return false;
            }
        });
    }

    @OnClick({R.id.title_bar, R.id.imageView7, R.id.iv_touxiang, R.id.tv_jishi, R.id.im_start, R.id.tv_Again, R.id.rl_bofangone, R.id.rl_bofangtwo, R.id.rl_bofangthree})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_bar:
                break;
            case R.id.imageView7:
                break;
            case R.id.iv_touxiang:
                setTitles();
                break;
            case R.id.tv_jishi:
                break;
            case R.id.im_start:
                break;
            case R.id.tv_Again:
                bofangLuyin();
                break;
            case R.id.rl_bofangone:
                break;
            case R.id.rl_bofangtwo:
                break;
            case R.id.rl_bofangthree:
                break;
        }
    }

    public void setTitles() {
        if (uploadImgAdapter == null) {
            initUploadImgAdapter();
        }
        uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
    }

    private void initUploadImgAdapter() {
        Log.e("TAG", "进入了方法");
        uploadImgAdapter = new UploadImgAdapter(SetInfomationTwoActivity.this, new UploadImgAdapter.Action2() {
            @Override
            public void call(File file, int mode) {
                ivTouxiang.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                File file1 = Compress.compressImage(file.getPath(), SetInfomationTwoActivity.this);


                OkHttpClient client=new OkHttpClient();
/*                Request request=new Request.Builder().url().build();*/

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }

    }


    /**
     * 播放录音
     **/
    public void bofangLuyin() {
        // TODO Auto-generated method stub
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(voiceName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "播放失败");
        }
    }

    /**
     * 停止播放
     **/
    public void stopBofang() {
        // TODO Auto-generated method stub
        mPlayer.release();
        mPlayer = null;
    }


    /**
     * 倒计时
     **/
    public void daoJishi(final TextView tv_jishi) {
        ToastUtil.show("进入了方法倒计时");
        countDownTimer = new CountDownTimer(1800000, 1) {

            String shijian;

            public void onTick(long millisUntilFinished) {
                haomiao++;
                if (haomiao == 60) {
                    haomiao = 0;
                    miao++;
                    if (miao == 60) {
                        miao = 0;
                        fen++;
                    }
                }
                shijian = xiaoshi + ":" + fen + ":" + miao + ":" + haomiao;
                tv_jishi.setText(shijian);

            }

            @Override
            public void onFinish() {

            }
        }.start();

    }


    public void onc() {

        del_re = (LinearLayout) this.findViewById(R.id.del_re);
        rcChat_popup = this.findViewById(R.id.rcChat_popup);
        voice_rcd_hint_rcding = (LinearLayout) this.findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) this.findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) this.findViewById(R.id.voice_rcd_hint_tooshort);
        img1 = (ImageView) this.findViewById(R.id.img1);
        sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);

        volume = (ImageView) this.findViewById(R.id.volume);
        mSensor = new SoundMeter();
    }


    public void onstarts() {

        rcChat_popup.setVisibility(View.VISIBLE);
        voice_rcd_hint_loading.setVisibility(View.VISIBLE);
        voice_rcd_hint_rcding.setVisibility(View.GONE);
        voice_rcd_hint_tooshort.setVisibility(View.GONE);
        mHandler.postDelayed(new Runnable() {
            public void run() {
                if (!isShosrt) {
                    voice_rcd_hint_loading.setVisibility(View.GONE);
                    voice_rcd_hint_rcding
                            .setVisibility(View.VISIBLE);
                }
            }
        }, 300);
        img1.setVisibility(View.VISIBLE);
        del_re.setVisibility(View.GONE);
        startVoiceT = System.currentTimeMillis();
        startVoiceT = SystemClock.currentThreadTimeMillis();

        start(voiceName);
        flag = 2;


    }

    public void onstorp() {

        rcChat_popup.setVisibility(View.GONE);
        img1.setVisibility(View.VISIBLE);
        del_re.setVisibility(View.GONE);
        stop();
        flag = 1;
    }

    private static final int POLL_INTERVAL = 300;

    private Runnable mSleepTask = new Runnable() {
        public void run() {
            stop();
        }
    };
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            updateDisplay(amp);
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);

        }
    };

    private void start(String name) {
        mSensor.start(name);
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    private void stop() {
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(mPollTask);
        mSensor.stop();
        volume.setImageResource(R.drawable.amp1);
    }

    private void updateDisplay(double signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                volume.setImageResource(R.drawable.amp1);
                break;
            case 2:
            case 3:
                volume.setImageResource(R.drawable.amp2);

                break;
            case 4:
            case 5:
                volume.setImageResource(R.drawable.amp3);
                break;
            case 6:
            case 7:
                volume.setImageResource(R.drawable.amp4);
                break;
            case 8:
            case 9:
                volume.setImageResource(R.drawable.amp5);
                break;
            case 10:
            case 11:
                volume.setImageResource(R.drawable.amp6);
                break;
            default:
                volume.setImageResource(R.drawable.amp7);
                break;
        }
    }


}
